package com.example.receiptocr.viewModels

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.receiptocr.api.ReceiptApi
import com.example.receiptocr.bodys.responseBodys.ReceiptInfo
import com.example.receiptocr.ocr.ReceiptData
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

sealed class DetailState {
    object Loading : DetailState()
    data class Success(val receiptInfo: ReceiptInfo) : DetailState()
    data class Error(val message: String) : DetailState()
}
@HiltViewModel
class DetailsViewModel @Inject constructor(
    private val api: ReceiptApi
) : ViewModel() {

    private val _detailState = MutableStateFlow<DetailState>(DetailState.Loading)
    val detailState: StateFlow<DetailState> = _detailState.asStateFlow()
    fun saveReceipt(receiptInfo: ReceiptInfo) {
        viewModelScope.launch {
            try {
                val response = api.updateReceipt(receiptInfo)
                if (!response.isSuccessful) {
                    _detailState.value = DetailState.Error("保存失败：${response.message()}")
                }
            } catch (e: Exception) {
                _detailState.value = DetailState.Error(e.message ?: "保存失败")
            }
        }
    }
}
